#include <stdio.h>
/*
  A company uses a public telephone to transmit data. The data is a four-digit integer, which is encrypted during the transmission process. The encryption rules are as follows:
  1) Add 5 to each digit, and then replace the number with the remainder of the sum divided by 10; 
  2) Swap the first and fourth digits; 
  3) Swap the second and third digits.
  Please develop a program for the encryption and decryption.
 */
void Encrypting(int aa[]) //加密
{
	int t;//中间变量
	for (int i = 0; i <= 3; i++)
	{
		aa[i] += 5;
		aa[i] %= 10;
	}
	for (int i = 0; i <= 3 / 2; i++)//i 可取0，1
	{
		t = aa[i];
		aa[i] = aa[3 - i];
		aa[3 - i] = t;
	}
}

void Decrypting(int aa[]) //解密
{
	int t;//中间变量

	//第二位和第三位交换
	t = aa[1];
	aa[1] = aa[2];
	aa[2] = t;
	//第1位和第4位交换
	t = aa[0];
	aa[0] = aa[3];
	aa[3] = t;
	//各位数加5，再模10
	for (int i = 0; i <= 3; i++)
	{
		aa[i] += 5;
		aa[i] %= 10;
	}

}

int main()
{
	int a, aa[4];
	char cmdChar;
	do
	{
        fflush(stdin);//清空键盘输入缓冲区
		printf("请输入命令（E:加密；D：解密；Q: quit）\n");
		scanf("%c", &cmdChar);
		switch (cmdChar)
		{
			case 'E':
				printf("请输入四位数字：");
				scanf("%d", &a);
				aa[0] = a % 10;
				aa[1] = a % 100 / 10;
				aa[2] = a % 1000 / 100;
				aa[3] = a / 1000;
				Encrypting(aa);
				printf("加密后的数字：");
				for (int i = 3; i >= 0; i--)
					printf("%d", aa[i]);
				printf("\n");
				break;
			case 'D':
				printf("请输入四位秘密数字：");
				scanf("%d", &a);
				aa[0] = a % 10;
				aa[1] = a % 100 / 10;
				aa[2] = a % 1000 / 100;
				aa[3] = a / 1000;
				Decrypting(aa);
				printf("解密后的数字：");
				for (int i = 3; i >= 0; i--)
					printf("%d", aa[i]);
				printf("\n");
				break;
			case 'Q':
				printf("Quit the program!\n");
				break;
			default:
				//TODO
				break;
		}
	}
	while (cmdChar != 'Q');
}


